﻿using TjZheng.Example.MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TjZheng.Framework;
using TjZheng.UpLoad;
using TjZheng.Controls;
using System.Text;
using System.Net;
using System.IO;

namespace TjZheng.Example.MVC.Controllers
{
    public class FilesController : Controller
    {
        public ActionResult FileUpload()
        {
            //string d = string.Format("{0}");
            return View();
        }

        public ActionResult Upload(FileEntity objFileEntity, HttpPostedFileWrapper objFile)
        {
            string savePath = HttpContext.Server.MapPath(string.Format("~/FileSource/{0}", objFile.FileName));
            string dataPath = string.Format("/FileSource/{0}", objFile.FileName);
            objFile.SaveAs(savePath);
            objFileEntity.Image = dataPath;
            return Json(objFileEntity);
        }

        public ActionResult FilesUpload()
        {
            return View("");
        }

        public ActionResult Uploads(HttpPostedFileWrapper objFile)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (Request["UpLoadSet"].IsNull())
            {
                objInvokeResult.ResultCode = "ParamsEmpty";
                objInvokeResult.ResultMessage = "上传配置参数不能为空";
                return Json(objInvokeResult);
            }
            var objUpLoadSet = Request["UpLoadSet"].JsonDeserialize<UpLoadSet>();
            if (objUpLoadSet == null)
            {
                objInvokeResult.ResultCode = "ParamsError";
                objInvokeResult.ResultMessage = "上传配置参数格式错误";
                return Json(objInvokeResult);
            }
            string objSavePath = HttpContext.Server.MapPath(string.Format("~/FileSource/{0}/{1}/{2}/{3}", objUpLoadSet.CategoryCode, objUpLoadSet.LimitCode, DateTime.Now.ToString("yyyyMMdd"), objFile.FileName));
            objFile.SaveAs(objSavePath.CreateDirectory());
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "上传成功";
            objInvokeResult.Data = string.Format("/FileSource/{0}/{1}/{2}/{3}", objUpLoadSet.CategoryCode, objUpLoadSet.LimitCode, DateTime.Now.ToString("yyyyMMdd"), objFile.FileName);
            return Json(objInvokeResult);
        }

        public ActionResult FileSet()
        {
            return View();
        }

        //public ActionResult SetUpload(UpLoadSet objUpLoadSet, HttpPostedFileWrapper objFile)
        //{
        //    return Json(objUpLoadSet);
        //}

        public ActionResult SetUpload(ZooEntity objZooEntity, string objName)
        {
            return Json(objZooEntity);
        }

        public ActionResult UpLoadControlTest()
        {
            return View();
        }

        /// <summary>
        /// 测试原生文件上传
        /// </summary>
        /// <returns></returns>
        public ActionResult TestFile()
        {
            FtpHelper objFtpHelper = new FtpHelper("tjzheng", "5201314..");
            //objFtpHelper.CreateDirectory("/Test/TestCreateFile");
            return View(objFtpHelper.GetDirectories("/"));
            //return View(GetFileList("/Systems"));//当前目录
            //return View(GetFileList("/Systems/"));//罗列子目录
            //return View(GetFileList("/Systems/Icons"));
            //return View(GetFileList("/Systems/Icons/"));
            //return View(GetFileList("/My"));///My not found 
            //return View(GetFileList("/My/"));//这种写法会出异常
        }

        public ActionResult FileSubmit(TestFileEntity objProvide)
        {
            var value = Request["objProvide.TestFile"];
            var file = Request.Files["objProvide.TestFile.File"] as HttpPostedFileWrapper;
            var set = Request["objProvide.TestFile.Set"];
            FtpHelper objFtpHelper = new FtpHelper("tjzheng", "5201314..");
            objFtpHelper.Upload(file, "/Test/TestCreateFile/" + file.FileName);
            //FTP或HTTP  跨域上传  经测试Htto不可取
            //var result = "http://tjzheng.example.com/files/crossdomain/".GetPageSource("value=1", "application/x-www-form-urlencoded", null, Encoding.UTF8);
            ////PostData objPostData = new PostData { Value = value, Set = set, File = file };
            ////var result = "http://tjzheng.example.com/files/crossdomain/".GetPageSource(objPostData.JsonSerialize());
            //return Content(result);

            //Upload(file);
            //CreateDirectory("/Test");
            //CreateDirectory("/Test/TestChild");//如果不存在Test文件夹，子目录的创建也会失败
            return Content("成功了");
        }

        void Upload(HttpPostedFileBase objFile)
        {
            string uri = "ftp://127.0.0.1/" + objFile.FileName;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Credentials = new NetworkCredential("tjzheng", "5201314..");
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = objFile.ContentLength;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            var fs = objFile.InputStream;
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception)
            {

            }
        }

        void CreateDirectory(string dirName)
        {
            string uri = "ftp://127.0.0.1" + dirName;
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential("tjzheng", "5201314..");
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception)
            {

            }
        }


        public string[] GetFileList(string mask)
        {
            string ftpURI = "ftp://127.0.0.1" + mask;
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential("tjzheng", "5201314..");
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                string line = reader.ReadLine();
                while (line != null)
                {
                    //result.Append(line);
                    if (!RegexHelper.IsMatch(line, @"\.+"))
                    {
                        result.Append(line);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如，未找到文件，无法访问文件)。")
                {

                }
                return downloadFiles;
            }
        }

        public ActionResult CrossDomain()
        {
            return Json(Request["value"]);
            //return Json(objPostData);
        }

        public ActionResult MultiFiles()
        {
            var objFiles = Request.Files.GetMultiple("tests");
            return View();
        }

        public ActionResult MultiFilesSave()
        {
            var objFiles = Request.Files.GetMultiple("objFile1");
            return Content("MultiFilesSave");
        }
    }

    public class PostData
    {
        public string Value { get; set; }
        public string Set { get; set; }
        public HttpPostedFileWrapper File { get; set; }
    }
}
